/**
 * Created by yangfan on 2016/9/21.
 */
define(['config/appregister',"i18n","config/editor","webuploader"],function(app,i18n,editor,WebUploader){
    app.directive("uploadSelect",function(){
        return {
            scope:{conf:"=uploadConf"},
            template:'<input type="file" id="file" ng-click="selectFile()"   style="width:238px;height:60px;opacity:0;cursor: pointer;"  />',
            link:function(scope,element,attrs){
                var file = document.getElementById("file");
                if(!scope.conf.url||!scope.conf.api){
                    return
                }
                var url = scope.conf.url + "/" + scope.conf.api;
                file.onchange = function () {
                    var ajaxFile=new uploadFile({
                        //"url":"http://115.29.168.57:8080/elink_database/api/file/upload",
                        url:url,
                        "dataType":"jsonp",
                        "timeout":5000,
                        "async":true,
                        "data":{
                            //多文件
//					"files":{
//						//file为name字段 后台可以通过$_FILES["file"]获得
//						"file":document.getElementById("file").files//文件数组
//					}
                            //单文件
                            "file":{
                                "file":document.getElementById("file").files[0],
                            },
                        },
                        onloadstart:function(){
                            //console.log("开始上传");
                        },
                        onload:function(data){
                            console.log(data);
                            console.log(data.name);
                        },
                        onerror:function(er){
                            console.log("上传失败XXX");
                        },
                        onabort:function(){
                            //alert("取消上传");
                            console.log("cancel");
                        },
                        ontimeout:function(){
                            //alert("上传时间到");
                        },
                        onloadend:function(data){
                            if(!data.response){
                                return
                            };
                            var json =JSON.parse(data.response);
                            scope.conf.path = json.data;

                        },
                        onprogress:function(e){
                            console.log(e);
                        }

                    });
                    scope.conf.onchange();
                }
            }
        }

    })
        .directive("uploadSet",function(){
            return {
                scope:{conf:"=uploadConf"},
                //comComponents:'<a ng-bind="i18n.selectFile" id="selectbtn"></a>',
                template:'<div id="uploader">'+
               '<div  type="button" id="picker" resetValue="0"  style="width: 0;height: 0;opacity: 0;display:block">'+'</div>'+
                '</div>',
                link:function(scope,element,attrs){
                    $("#btn_confirm_add").hide();
                    var userInfo = {
                        userId: "1111",
                        fileType: "0"
                    }; //用户会话信息
                    var chunkSize = 5000 * 1024; //分块大小
                    var uniqueFileName = null; //文件唯一标识符
                    var md5Mark = null;
                    var removeChildNodes = function($, own) {
                        if($ == null) {
                            return;
                        }
                        while($.hasChildNodes()) {
                            $.removeChild($.firstChild);
                        }
                        if(own) {
                            $.parentNode.removeChild($);
                        }
                    };

                    function getServer(type) { //测试用，根据不同类型的后端返回对应的请求地址
                        switch(type) {
                            case "php":
                                return "./serverPHP/fileUpload.php"
                            case "node":
                                return "http://localhost:3000/fileUpload";
                            case "java":
                                return scope.conf.url+"/"+scope.conf.api;
                            case "dubbo":
                                return "http://127.0.0.1:8888/fileUpload";
                        }
                    }

                    var backEndUrl = getServer("java");

                    WebUploader.Uploader.register({
                        "add-file":"addFile",
                        "before-send-file": "beforeSendFile",
                        "before-send": "beforeSend",
                        "after-send-file": "afterSendFile"
                    }, {
                        addFile:function(file){
                          console.log(file);
                        },
                        beforeSendFile: function(file) {
                            //秒传验证
                            var task = new $.Deferred();
                            var start = new Date().getTime();
                            (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function(percentage) {
                                console.log(percentage);
                            }).then(function(val) {
                                console.log("总耗时: " + ((new Date().getTime()) - start) / 1000);

                                md5Mark = val;
                                userInfo.md5 = val;
                                console.log(1);
                                $.ajax({
                                    type: "POST",
                                    url: backEndUrl,
                                    data: {
                                        status: "md5Check",
                                        md5: val
                                    },
                                    cache: false,
                                    timeout: 1000 //todo 超时的话，只能认为该文件不曾上传过
                                    ,
                                    dataType: "json"
                                }).then(function(data, textStatus, jqXHR) {

                                    //console.log(data);
                                    scope.conf.path = data.path;
                                    scope.$emit("uploadSuccess",{path:data.path});

                                    if(data.ifExist) { //若存在，这返回失败给WebUploader，表明该文件不需要上传
                                        task.reject();
                                        uploader.skipFile(file);
                                        file.path = data.path;
                                        UploadComlate(file);
                                    } else {
                                        task.resolve();
                                        //拿到上传文件的唯一名称，用于断点续传
                                      //  uniqueFileName = md5(file.name + file.type + file.lastModifiedDate + file.size);
                                    }
                                }, function(jqXHR, textStatus, errorThrown) { //任何形式的验证失败，都触发重新上传
                                    task.resolve();
                                    //拿到上传文件的唯一名称，用于断点续传
                                    uniqueFileName = md5(file.name + file.type + file.lastModifiedDate + file.size);
                                });
                            });
                            return $.when(task);
                        },
                        beforeSend: function(block) {
                            //分片验证是否已传过，用于断点续传
                            var task = new $.Deferred();
                            console.log(2);
                            $.ajax({
                                type: "POST",
                                url: backEndUrl,
                                data: {
                                    status: "chunkCheck",
                                    name: uniqueFileName,
                                    chunkIndex: block.chunk,
                                    size: block.end - block.start,
                                    fileType: userInfo.fileType
                                },
                                cache: false,
                                timeout: 1000 //todo 超时的话，只能认为该分片未上传过
                                ,
                                dataType: "json"
                            }).then(function(data, textStatus, jqXHR) {
                                if(data.ifExist) { //若存在，返回失败给WebUploader，表明该分块不需要上传
                                    task.reject();
                                } else {
                                    task.resolve();
                                }
                            }, function(jqXHR, textStatus, errorThrown) { //任何形式的验证失败，都触发重新上传
                                task.resolve();
                            });

                            return $.when(task);
                        },
                        afterSendFile: function(file, data) {
                            var chunksTotal = 0;
                            if((chunksTotal = Math.ceil(file.size / chunkSize)) > 1) {
                                //合并请求
                                var task = new $.Deferred();
                                console.log(3);
                                $.ajax({
                                    type: "POST",
                                    url: backEndUrl,
                                    data: {
                                        status: "chunksMerge",
                                        name: uniqueFileName,
                                        chunks: chunksTotal,
                                        ext: file.ext,
                                        md5: md5Mark,
                                        fileType: userInfo.fileType,
                                        fileName: file.name
                                    },
                                    cache: false,
                                    dataType: "json"
                                }).then(function(data, textStatus, jqXHR) {

                                    //todo 检查响应是否正常

                                    task.resolve();
                                    file.path = data.path;
                                    UploadComlate(file);

                                }, function(jqXHR, textStatus, errorThrown) {
                                    task.reject();
                                });

                                return $.when(task);
                            } else {
                                file.path = data.path;
                                UploadComlate(file);
                            }
                        }
                    });

                    var uploader = WebUploader.create({
                        auto:true,
                        swf: "Uploader.swf",
                        server: backEndUrl,
                        pick: $('#picker'),
                        resize: false,
                        duplicate: true,
                        //dnd: "#theList",
                        paste: document.body,
                        disableGlobalDnd: true,
                        //				, compress: {
                        //					quality: 90
                        //					, allowMagnify: false
                        //					, crop: false
                        //					, preserveHeaders: true
                        //					, noCompressIfLarger: true
                        //					,compressSize: 100000
                        //				}
                        compress: null,
                        prepareNextFile: true,
                        chunked: true,
                        chunkSize: chunkSize,
                        threads: true,
                        formData: function() {
                            return $.extend(true, {}, userInfo);
                        },
                        fileNumLimit: 1,
                        fileSingleSizeLimit: 1000 * 1024 * 1024 * 1024,
                        duplicate: true
                    });

                    //			<button id="upload" class="btn btn-default">开始上传</button>
                    //			<button id="cancel" class="btn btn-default">取消</button>
                    uploader.on("fileQueued", function(file ) {
                        scope.conf.file = file;
                        //$(".webuploader-pick").text("重新上传");
                        //				$("#theList").append('<li id="' + file.id + '">' +
                        //					'<img /><span>' + file.name + '</span><span class="itemUpload">上传</span><span class="itemStop">暂停</span><span class="itemDel">删除</span>' +
                        //					'<div class="percentage"></div>' +
                        //					'</li>');
                        //$("#uploader").append(
                        //	'<button id="itemUpload" class="btn btn-default">开始上传</button><button id="itemStop" class="btn btn-default">暂停上传</button>'
                        //);
//				$("#theList").append('<li id="' + file.id + '">' +
////					'<img />' +
//					'<div class="percentage"></div>' +
//					'</li>');
                        var $img = $("#" + file.id).find("img");
                        uploader.upload();

                        /*uploader.makeThumb(file, function(error, src) {
                            if(error) {
                                $img.replaceWith("<span>无预览</span>");
                            }

                            $img.attr("src", src);
                        });*/
                        //	$("#itemFileName").text(file.name);

                    });
                    uploader.on("uploadStart",function(file,response){
                        console.log(file)
                    });
                    $("#picker").click(function() {
                        var a = $("#picker").find("div").eq(1);
                        if($("#picker").attr("resetValue") == 1) {
                            uploader.reset();
                            removeChildNodes(document.getElementById("theList"));
                            removeChildNodes(document.getElementById("itemUpload"), true);
                            removeChildNodes(document.getElementById("itemStop"), true);
                            removeChildNodes(document.getElementById("itemSuccess"), true);
                        } else {
                            $("#picker").attr("resetValue", 1);
                        }
                    });
                    $("#uploader").on("click", "#itemUpload", function() {
                        uploader.upload();

                        //"上传"-->"暂停"
                        $(this).hide();
                        $("#itemStop").show();
                    });

                    $("#uploader").on("click", "#itemStop", function() {
                        uploader.stop(true);
                        //"暂停"-->"上传"
                        $(this).hide();
                        $("#itemUpload").show().text("继续上传");
                    });

                    //todo 如果要删除的文件正在上传（包括暂停），则需要发送给后端一个请求用来清除服务器端的缓存文件 未实现
                    $("#uploader").on("click", "#itemDel", function() {
                        uploader.removeFile($(this).parent().attr("id")); //从上传文件列表中删除
                        $(this).parent().remove(); //从上传列表dom中删除
                    });
//			uploader.on("uploadProgress", function(file, percentage){
//				$("#" + file.id + " .percentage").text(percentage * 100 + "%");
//			});
                    // 文件上传过程中创建进度条实时显示。
                    uploader.on('uploadProgress', function(file, percentage) {
                        var $li = $('#ossfile'),
                            $percent = $li.find('.progress .progress-bar');
                        // 避免重复创建
                        if(!$percent.length) {
                            $percent = $('<div id="progressParent" class="progress progress-striped active">' +
                                '<div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;">' +
                                '</div>' +
                                '</div>').appendTo($li).find('.progress-bar');
                        }

//				$li.find('p.state').text('上传中');
                        $percent.css('width', percentage * 100 + '%');
                        $("#progressBar").css('width',percentage * 100 + '%');
//				$("#" + file.id + " .percentage").text(percentage * 100 + "%");
                        $("#progressBar").text(parseInt((parseFloat($("#progressBar").css("width")) / parseFloat($("#progressParent").css("width")) * 100))+ "%");
//				$("#" + file.id + " .percentage").text(parseInt((parseFloat($("#progressBar").css("width")) / parseFloat($("#progressParent").css("width")) * 100)));
                    });
                    uploader.on("uploadSuccess",function(file,response){
                        scope.$emit("uploadSuccess",response);
                    });
                    uploader.on( 'uploadError', function( file ) {
                        console.log(file)
                    })
                    function UploadComlate(file) {
//				$("#" + file.id + " .percentage").text("上传完毕");
//				$("#uploader").append(
//						'<button id="itemSuccess" class="btn btn-default">上传成功</button>'
//					);
//				console.log(file.size);
                        $("#progressBar").text("100%");
                        $("#url").val(file.path);
                        $("#fileSize").val(file.size);
                        $("#itemStop").hide();
                        $("#itemUpload").hide();
                        $("#btn_confirm_add").show();
                    }

                }
            }
        } )

});
